/*
 Rilego - An easy Images 2 E-Book converter.
Copyright (C) 2011  Federico Improta (Kirys)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/

package it.kirys.rilego.gui.filtersmanager;

import it.kirys.rilego.gui.filtersmanager.setters.IFilterSetter;
import java.util.LinkedList;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author Federico Improta
 */
public class FiltersTreeModel implements TreeModel{
	FiltersManager manager;
	String root="Filters";
	LinkedList<TreeModelListener> list;
	protected static class FiltersTreeListener implements TreeSelectionListener{

		@Override
		public void valueChanged(TreeSelectionEvent e) {
		}
	}

	public void applyToTree(JTree t){
		t.setModel(this);
		t.setRootVisible(false);
	}//void applyToTree(JTree t)

	@Override
	public Object getRoot() {
		return root;
	}

	@Override
	public Object getChild(Object parent, int index) {
		if (parent==root){
			return manager.get(index);
		}  else if (parent instanceof IFilterSetter){
			return ((IFilterSetter)parent).getPrefs().get(index);
		} else {
			return null;
		}
	}

	@Override
	public int getChildCount(Object parent) {
		if (parent==root){
			if (manager!=null){
			return manager.size();
			} else {
				return 0;
			}
		} else if (parent instanceof IFilterSetter){
			return ((IFilterSetter)parent).getPrefs().size();
		} else {
			return 0;
		}
	}

	@Override
	public boolean isLeaf(Object node) {
		return getChildCount(node)==0;
	}

	@Override
	public void valueForPathChanged(TreePath path, Object newValue) {
		TreeModelEvent e= new TreeModelEvent(newValue, path);
		for (TreeModelListener ml:list){
			ml.treeNodesChanged(e);
		}
	}

	@Override
	public int getIndexOfChild(Object parent, Object child) {
		return 0;
	}

	@Override
	public void addTreeModelListener(TreeModelListener l) {
		this.list.add(l);
	}

	@Override
	public void removeTreeModelListener(TreeModelListener l) {
		this.list.remove(l);
	}

	public FiltersTreeModel(FiltersManager manager) {
		this.manager= manager;
		this.list = new LinkedList<TreeModelListener>();
	}


}
